from PIL import Image
from flask import request, Blueprint, jsonify, url_for, send_from_directory
import os

blueprint = Blueprint("convertImg", __name__)
upload = "upload/"


def createFolder(folder_path):
    """
    文件夹路径不存在则创建
    :param folder_path: 文件夹路径
    :return: 创建后的文件夹路径
    """
    root_directory = os.getcwd()
    folder = os.path.join(root_directory, folder_path)
    if not os.path.exists(folder):
        os.makedirs(folder)
    return folder


def getImgBlueprint():
    """
    返回蓝图对象
    :return:  蓝图对象
    """
    return blueprint


def convert_to_icon(file_name, size=(32, 32)):
    """
    转换为图标
    :param size: 尺寸
    :param file_name: 文件名称
    :return:
    """
    path = os.path.join(upload, file_name)
    img = Image.open(path)
    folder = createFolder(upload + "ico")
    img.save(folder + "/" + file_name + ".ico", format="ICO", sizes=[size])
    # 删除上传的图片
    os.remove(path)


# 处理上传的图片
@blueprint.route('/upload', methods=['get', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['file']
        createFolder(upload)
        f.save(os.path.join(upload, f.filename))
        # 设置转换后的 ICO 尺寸
        icon_size = (64, 64)
        convert_to_icon(f.filename, size=icon_size)
        return jsonify(success=True, msg="上传成功", code=200)
    return jsonify(success=True, msg="不支持的请求", code=500)


@blueprint.route('/transfer', methods=['POST'])
def transfer():
    """
    图片转换
    :return:
    """
    f = request.files['file']
    ext = request.form['ext']
    createFolder(upload + "transfer")
    path = os.path.join(upload + "transfer/", f.filename)
    f.save(path)
    img = Image.open(path)
    try:
        r, g, b, a = img.split()
    except:
        r, g, b = img.split()
    img = Image.merge('RGB', (r, g, b))
    img.save(path + '.' + ext)
    image_url = url_for('static', filename=path, _external=True)
    return jsonify(code=200, message="成功", data=image_url)


@blueprint.route('/upload/transfer/<filename>')
def preview_image(filename):
    """
    将图片映射给浏览器[图片预览]
    :param filename: 图片名
    :return: 图片
    """
    path = os.path.join(upload, "transfer/")
    image_url = send_from_directory(path, filename)
    return image_url
